import { TodoForm, TodoList, TodoItem } from './views';
import model from './model';

(() => {
  const oApp = document.getElementById('app');
  const todoModel = model.create();
  const nodes = {};

  const init = () => {
    render(todoModel.todoData); //首次渲染
    getNodes(); //节点获取
    bindEvent(); //事件绑定
  };

  function render(data) {
    const oFrag = document.createDocumentFragment();
    oFrag.appendChild(TodoForm());
    oFrag.appendChild(TodoList(data));
    oApp.appendChild(oFrag);
  }

  function getNodes() {
    nodes.oTodoInput = oApp.querySelector('#J_TodoInput');
    nodes.oAddBtn = oApp.querySelector('#J_AddBtn');
    nodes.oList = oApp.querySelector('#J_TodoList');
  }

  function bindEvent() {
    nodes.oAddBtn.addEventListener('click', handleAddBtnClick, false);
    nodes.oList.addEventListener('click', handleListClick, false);
  }

  //-----------------处理事件相关-----------------------

  function handleAddBtnClick() {
    const text = nodes.oTodoInput.value;
    if (text.length === 0) return;
    todoModel.setTodoText(text);
    todoModel.addTodo(todoModel.todoText, (todo) => {
      // console.log(todo); //{id: 1678470250333, content: '111', completed: false}
      // console.log(TodoItem(todo)); //<li>...</li>
      appendItem(TodoItem(todo));
    });
  }

  function handleListClick(e) {
    const tar = e.target;
    const tagName = tar.tagName;
    switch (tagName) {
      case 'INPUT':
        handleCheckboxClick(tar);
        break;
      case 'BUTTON':
        handleDeleteBtnClick(tar);
        break;
      default:
        break;
    }
  }

  function handleCheckboxClick(tar) {
    const id = Number(tar.dataset.id);
    todoModel.toggleTodo(id, () => toggleItem(tar));
  }

  function handleDeleteBtnClick(tar) {
    const id = tar.dataset.id;
    todoModel.removeTodo(id, () => removeItem(tar));
  }

  //-----------------处理视图更新相关-----------------------
  function appendItem(item) {
    nodes.oList.appendChild(item);
    nodes.oTodoInput.value = '';
  }

  function toggleItem(tar) {
    tar.parentNode.querySelector('span').style.textDecoration = tar.checked
      ? 'line-through'
      : '';
  }

  function removeItem(tar) {
    tar.parentNode.remove();
  }

  init();
})();
